import * as vscode from "vscode";
import { exec } from "child_process";
import { join } from "path";
import { readFileSync, existsSync } from "fs";

function getShellType(): string | undefined {
  // 根据运行平台获取对应的shell配置键
  const platform = process.platform;
  const shellConfigKey =
    platform === "win32"
      ? "integrated.shell.windows"
      : platform === "darwin"
      ? "integrated.shell.osx"
      : "integrated.shell.linux";

  // 获取当前终端的shell路径配置
  const shellConfig = vscode.workspace.getConfiguration("terminal");
  const shellPath = shellConfig.get<string>(shellConfigKey);
  return shellPath;
}

function switchNodeVersion(version: string): Promise<void> {
  return new Promise((resolve, reject) => {
    const command = `nvm use ${version}`;

    exec(command, (error, stdout, stderr) => {
      console.log(`执行命令: ${error}`);
      console.log(`执行命令: ${stdout}`);
      console.log(`执行命令: ${stderr}`);

      if (error || stderr || stdout.indexOf("is not installed") > -1) {
        // 如果nvm use失败，尝试nvm install
        vscode.window
          .showErrorMessage(`${version}版本不存在，是否需要安装？`, "是", "否")
          .then((value) => {
            if (value === "是") {
              // 安装版本，并切换
              exec(
                `nvm install ${version}`,
                (installError, installStdout, installStderr) => {
                  if (installError) {
                    reject(installStderr);
                  } else {
                    // 安装成功后再次尝试切换版本
                    exec(
                      `nvm use ${version}`,
                      (useError, useStdout, useStderr) => {
                        if (useError || useStderr) {
                          reject(useStderr);
                        } else {
                          resolve();
                        }
                      }
                    );
                  }
                }
              );
            }
          });
      } else {
        resolve();
      }
    });
  });
}

export function activate(context: vscode.ExtensionContext) {
  // console.log('Congratulations, your extension "nvm-auto-node" is now active!');
  // const terminals = vscode.window.terminals;
  // const sendText = (t: vscode.Terminal) => t.sendText("nvm use");
  // if (terminals.length) {
  //   console.log("Found opened terminals, let's change node version");
  //   terminals.forEach(sendText);
  // }
  // vscode.window.onDidOpenTerminal(sendText);

  const disposable = vscode.commands.registerCommand(
    "nvm-auto-node.nvmAutoNode",
    () => {
      vscode.window.showInformationMessage("正在尝试切换Node版本,请稍后...!");
      // 获取工作区目录
      // console.log(`获取工作区目录: ${vscode.workspace.workspaceFolders}`);
      if (!vscode.workspace.workspaceFolders) {
        return;
      }
      // 获取工作区目录路径
      const path = vscode.workspace.workspaceFolders[0].uri.fsPath;
      // console.log(`获取工作区目录路径: ${path}`);

      // 获取package.json
      const packageJsonFilePath = join(path, "/package.json");
      // console.log(`获取package.json: ${packageJsonFilePath}`);

      // 检查打开的项目中是否有package.json
      if (!existsSync(packageJsonFilePath)) {
        vscode.window.showErrorMessage("切换Node版本失败: 缺少package.json!");
        return;
      }

      // 读取package.json
      let packageJsonString = readFileSync(
        packageJsonFilePath,
        "utf8"
      ).toString();
      // console.log(`读取package.json: ${packageJsonString}`);

      if (!packageJsonString) {
        vscode.window.showErrorMessage(
          "切换Node版本失败: 读取package.json失败!"
        );
        return;
      }

      // 解析package.json
      const packageJson = JSON.parse(packageJsonString);

      // 检查是否有nodeVersion
      if (!packageJson.nodeVersion) {
        vscode.window.showErrorMessage(
          "切换Node版本失败: package.json中未配置nodeVersion!"
        );
        return;
      }

      const { nodeVersion } = packageJson;
      // console.log(`nodeVersion: ${nodeVersion}`);

      // 获取当前终端的shell类型
      // const shell = getShellType();
      // if (shell) {
      //   console.log(`Current terminal shell type: ${shell}`);
      // } else {
      //   console.log("Shell type not found");
      // }

      switchNodeVersion(nodeVersion)
        .then(() => {
          vscode.window.showInformationMessage(
            `切换Node.js版本成功: ${nodeVersion}!`
          );
        })
        .catch((error) => {
          vscode.window.showErrorMessage(`切换Node.js版本失败: ${error}`);
        });
    }
  );

  context.subscriptions.push(disposable);
}

export function deactivate() {}
